package com.example.service.aboutStudent.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.vo.request.OperateStudentForm;
import com.example.vo.request.SearchStudentConditions;
import com.example.vo.response.StudentDTO;
import com.example.mapper.aboutStudent.StudentMapper;
import com.example.pojo.aboutStudent.Student;
import com.example.pojo.aboutStudent.StudentMoreInfo;
import com.example.service.aboutStudent.StudentMoreInfoService;
import com.example.service.aboutStudent.StudentService;
import com.example.vo.Result;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.lang.reflect.Field;
import java.util.Objects;

import static com.example.utils.SystemConstants.PHONE_ENCRYPT_KEY;

@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {

    @Resource
    private StudentMoreInfoService studentMoreInfoService;

    @Override
    public Result listStudents(Integer currentPage, Integer pageSize) {
        LambdaQueryWrapper<Student> studentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        studentLambdaQueryWrapper.eq(Student::getIsDelete, false).orderByDesc(Student::getUpdateTime);

        // db查询
        Page<Student> studentPage = super.page(new Page<>(currentPage, pageSize), studentLambdaQueryWrapper);

        Page<StudentDTO> studentDTOPage = this.packingPageStudentDTO(studentPage);

        return Result.success(studentDTOPage);
    }

    @Override
    @Transactional
    public Result saveStudent(OperateStudentForm operateStudentForm) {

        // 去除字符串两边的空格
        Field[] fields = operateStudentForm.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (String.class.equals(field.getType())) {
                try {
                    field.setAccessible(true);
                    String value = (String) field.get(operateStudentForm);
                    if (value != null) {
                        String trimmedValue = value.trim();
                        field.set(operateStudentForm, trimmedValue);
                    }
                } catch (IllegalAccessException e) {
                    // 忽略异常，继续处理下一个字段
                }
            }
        }

        Student student = BeanUtil.copyProperties(operateStudentForm, Student.class);

        StudentMoreInfo studentMoreInfo = BeanUtil.copyProperties(operateStudentForm, StudentMoreInfo.class);

        studentMoreInfoService.save(studentMoreInfo);

        student.setMoreInfo(studentMoreInfo.getId());

        if (!Objects.equals(student.getTelephone(), "") && student.getTelephone() != null) {
            // 手机号加密
            byte[] encrypt = SecureUtil.aes(PHONE_ENCRYPT_KEY.getBytes()).encrypt(student.getTelephone());
            student.setTelephone(HexUtil.encodeHexStr(encrypt));
        }

        if(student.getCollege() == null) {
            student.setCollege("计算机学院");
        }

        super.save(student);



        return Result.success();
    }

    @Override
    @Transactional
    public Result updateStudent(OperateStudentForm operateStudentForm) {

        Student student = BeanUtil.copyProperties(operateStudentForm, Student.class);

        StudentMoreInfo studentMoreInfo = BeanUtil.copyProperties(operateStudentForm, StudentMoreInfo.class);

        studentMoreInfo.setId(student.getMoreInfo());
        studentMoreInfoService.updateById(studentMoreInfo);

        if (!Objects.equals(student.getTelephone(), "")) {
            // 手机号加密
            byte[] encrypt = SecureUtil.aes(PHONE_ENCRYPT_KEY.getBytes()).encrypt(student.getTelephone());
            student.setTelephone(HexUtil.encodeHexStr(encrypt));
        }

        super.updateById(student);

        return Result.success();
    }

    @Override
    @Transactional
    public Result deleteStudent(StudentDTO studentDTO) {

        LambdaQueryWrapper<Student> studentLambdaQueryWrapper = new LambdaQueryWrapper<>();

        studentLambdaQueryWrapper.eq(Student::getId, studentDTO.getId());

        super.remove(studentLambdaQueryWrapper);

        LambdaQueryWrapper<StudentMoreInfo> studentMoreInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();

        studentMoreInfoLambdaQueryWrapper.eq(StudentMoreInfo::getId, studentDTO.getMoreInfo());

        studentMoreInfoService.remove(studentMoreInfoLambdaQueryWrapper);

        return Result.success();
    }


    @Override
    public Result listStudentsByConditions(SearchStudentConditions searchStudentConditions) {

        String name = searchStudentConditions.getName();
        String major = searchStudentConditions.getMajor();
        String classN = searchStudentConditions.getClassN();
        String province = searchStudentConditions.getProvince();
        String stuId = searchStudentConditions.getStuId();
        String enrollYear = searchStudentConditions.getEnrollYear();

        Integer currentPage = searchStudentConditions.getCurrentPage();
        Integer pageSize = searchStudentConditions.getPageSize();


        LambdaQueryWrapper<Student> studentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        studentLambdaQueryWrapper.eq(!name.equals(""), Student::getName, name)
                .eq(!major.equals(""), Student::getMajor, major)
                .eq(!classN.equals(""), Student::getClassN, classN)
                .eq(!province.equals(""), Student::getOriginArea, province)
                .eq(!stuId.equals(""), Student::getStuId, stuId)
                .eq(!enrollYear.equals(""), Student::getGrade, enrollYear)
                .orderByDesc(Student::getUpdateTime);

        // db查询
        Page<Student> page = super.page(new Page<>(currentPage, pageSize), studentLambdaQueryWrapper);

        Page<StudentDTO> studentDTOPage = this.packingPageStudentDTO(page);

        return Result.success(studentDTOPage);
    }


    // StudentDTO的组装

    private Page<StudentDTO> packingPageStudentDTO(Page<Student> page) {
        // 组装DTO对象
        Page<StudentDTO> studentDTOPage = new Page<>();
        BeanUtil.copyProperties(page, studentDTOPage);

        // Student对象转化为DTO对象并存储在Page<StudentDTO>对象中
        studentDTOPage.setRecords(BeanUtil.copyToList(page.getRecords(), StudentDTO.class));

        // 手机号解密
        for (StudentDTO studentDTO : studentDTOPage.getRecords()) {
            if (!Objects.equals(studentDTO.getTelephone(), "") && studentDTO.getTelephone() != null) {
                studentDTO.setTelephone(SecureUtil.aes(PHONE_ENCRYPT_KEY.getBytes()).decryptStr(studentDTO.getTelephone()));
            }
        }

        return studentDTOPage;
    }
}
